package ru.agiledev.akb.client.window;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import ru.agiledev.akb.client.*;
import ru.agiledev.akb.shared.User;

/**
 * Created by a.kirillov
 * Date: 5/16/11 Time: 10:13 PM
 */
public class EditPasswordWindow extends DialogBox {

    private TextBox oldPasswordField;
    private PasswordTextBox passwordField;
    private PasswordTextBox passwordConfirmField;
    private HorizontalPanel oldPasswordError;
    private HorizontalPanel passwordError;
    private HorizontalPanel passwordConfirmError;


    private final ValidationServiceAsync validationService = GWT.create(ValidationService.class);
    private final RegistrationServiceAsync registrationService = GWT.create(RegistrationService.class);

    public EditPasswordWindow(int x, int y) {
        setModal(true);
        setAnimationEnabled(true);
        setText("Регистрация");
        addStyleName("editPasswordDialogBox");
        setPopupPosition(x, y);

        VerticalPanel registrationPanel = new VerticalPanel();
        registrationPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);


        HorizontalPanel words = new HorizontalPanel();
        HTML hello = new HTML("<center>Для смены пароля необходимо ввести старый пароль.<center>");
        words.add(hello);

        HorizontalPanel enterYourData = new HorizontalPanel();
        enterYourData.setSpacing(4);
        enterYourData.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
        HTML inputPrompt = new HTML("<b>Заполните форму</b>");
        enterYourData.add(inputPrompt);

        HorizontalPanel oldPasswordPanel = new HorizontalPanel();
        oldPasswordPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
        oldPasswordPanel.setSpacing(4);
        oldPasswordField = new PasswordTextBox();
        oldPasswordField.getElement().setId("oldPwd");
        Label oldPassword = new Label("Старый пароль");

        oldPasswordPanel.add(oldPassword);
        oldPasswordPanel.add(oldPasswordField);

        oldPasswordError = new HorizontalPanel();
        oldPasswordError.setSpacing(2);

        HorizontalPanel passwordPanel = new HorizontalPanel();
        passwordPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
        passwordPanel.setSpacing(4);
        passwordField = new PasswordTextBox();
        passwordField.getElement().setId("pwd");
        Label password = new Label("Новый пароль");

        passwordPanel.add(password);
        passwordPanel.add(passwordField);

        passwordError = new HorizontalPanel();
        passwordError.setSpacing(2);

        HorizontalPanel passwordConfirmPanel = new HorizontalPanel();
        passwordConfirmPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
        passwordConfirmPanel.setSpacing(4);
        Label passwordConfirm = new Label("Подтвердите пароль");
        passwordConfirmField = new PasswordTextBox();
        passwordConfirmField.getElement().setId("pwdConfirm");

        passwordConfirmPanel.add(passwordConfirm);
        passwordConfirmPanel.add(passwordConfirmField);

        passwordConfirmError = new HorizontalPanel();
        passwordConfirmError.setSpacing(2);

        HorizontalPanel buttons = new HorizontalPanel();
        buttons.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
        buttons.setSpacing(4);
        Button confirm = new Button("Сохранить");

        confirm.addClickHandler(new RegistrationHandler());

        Button cancel = new Button("Отменить");
        cancel.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                hide();
            }
        });

        buttons.add(confirm);
        buttons.add(cancel);

        registrationPanel.add(hello);
        registrationPanel.add(enterYourData);
        registrationPanel.add(oldPasswordPanel);
        registrationPanel.add(oldPasswordError);
        registrationPanel.add(passwordPanel);
        registrationPanel.add(passwordError);
        registrationPanel.add(passwordConfirmPanel);
        registrationPanel.add(passwordConfirmError);
        registrationPanel.add(buttons);

        add(registrationPanel);


        //======================== Field focus listeners =====================

        oldPasswordField.addFocusHandler(new FieldFocusHandler());
        oldPasswordField.addBlurHandler(new FieldBlurHandler());
        passwordField.addFocusHandler(new FieldFocusHandler());
        passwordField.addBlurHandler(new FieldBlurHandler());
        passwordConfirmField.addFocusHandler(new FieldFocusHandler());
        passwordConfirmField.addBlurHandler(new FieldBlurHandler());

    }


    class FieldBlurHandler implements BlurHandler {
        @Override
        public void onBlur(BlurEvent event) {
            Element e = ((TextBox)event.getSource()).getElement();

            if("pwd".equals(e.getId())){
                AsyncCallback<Boolean> validation = new AsyncCallback<Boolean>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        //TODO: serverError
                    }

                    @Override
                    public void onSuccess(Boolean result) {
                        if(!result){
                            HTML error = new HTML("Допустимы латинские буквы и цифры.<br>Длина пароля не менее 5 символов.");
                            error.setStyleName("loginErrorPanel");
                            passwordError.add(error);
                            Element e = passwordField.getElement();
                            DOM.setStyleAttribute(e, "background", "orange");
                        }
                    }
                };

                validationService.validateLogin(passwordField.getText(), validation);
            }

            if("pwdConfirm".equals(e.getId())){
                if(!passwordField.getText().equals(passwordConfirmField.getText())){
                    HTML error = new HTML("Пароли не совпадают.");
                    error.setStyleName("loginErrorPanel");
                    passwordConfirmError.add(error);

                    DOM.setStyleAttribute(e, "background", "orange");
                }
            }
        }
    }

    class FieldFocusHandler implements FocusHandler {
        @Override
        public void onFocus(FocusEvent focusEvent) {

            Element e = ((TextBox)focusEvent.getSource()).getElement();
            if("oldPwd".equals(e.getId())){
                    DOM.setStyleAttribute(e, "background", "white");

                    if((oldPasswordError.getWidgetCount()>0)&&(oldPasswordError.getWidget(0)!=null)){
                        oldPasswordError.remove(0);
                    }
                }

            if("pwd".equals(e.getId())){
                    DOM.setStyleAttribute(e, "background", "white");

                    if((passwordError.getWidgetCount()>0)&&(passwordError.getWidget(0)!=null)){
                        passwordError.remove(0);
                    }
                }

            if("pwdConfirm".equals(e.getId())){
                    DOM.setStyleAttribute(e, "background", "white");

                    if((passwordConfirmError.getWidgetCount()>0)&&(passwordConfirmError.getWidget(0)!=null)){
                        passwordConfirmError.remove(0);
                    }
                }
        }
    }

    class RegistrationHandler implements ClickHandler {
        @Override
        public void onClick(ClickEvent clickEvent) {

            String oldPassword = oldPasswordField.getText();
            String password = passwordField.getText();
            String confirmPassword = passwordConfirmField.getText();

            boolean error = false;

            //Last name validation
            if(password.length()==0){

                Element e = passwordField.getElement();
                DOM.setStyleAttribute(e, "background", "orange");
                error = true;
            }

            if(confirmPassword.length()==0){

                Element e = passwordConfirmField.getElement();
                DOM.setStyleAttribute(e, "background", "orange");
                error = true;
            }

            if( (oldPasswordError.getWidgetCount()>0)&&(oldPasswordError.getWidget(0)!=null) ||
                (passwordError.getWidgetCount()>0)&&(passwordError.getWidget(0)!=null) ||
                (passwordConfirmError.getWidgetCount()>0)&&(passwordConfirmError.getWidget(0)!=null)){

                error = true;
            }


            if(!error){
                AsyncCallback<Void> registration = new AsyncCallback<Void>() {
                    @Override
                    public void onFailure(Throwable caught) {
                       HTML error = new HTML(caught.getMessage());
                    error.setStyleName("loginErrorPanel");
                    oldPasswordError.add(error);

                    DOM.setStyleAttribute(oldPasswordField.getElement(), "background", "orange");
                    }

                    @Override
                    public void onSuccess(Void result) {
                        hide();

                        final DialogBox dialogBox = new DialogBox();
                        dialogBox.setPopupPosition(RootPanel.get().getOffsetWidth()/2-160, RootPanel.get().getOffsetHeight()/2-150);
                        dialogBox.setText("Данные сохранены");
                        dialogBox.setWidth("310px");
                        dialogBox.setHeight("100px");
                        dialogBox.setModal(true);

                        VerticalPanel dialogPanel = new VerticalPanel();
                        dialogPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);


                        dialogPanel.add(new HTML("<center>Данные были успешно сохранены.</center>"));
                        HorizontalPanel dialogBoxButtons = new HorizontalPanel();
                        dialogBoxButtons.setSpacing(4);
                        dialogBoxButtons.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
                        Button ok = new Button("Ок");
                        ok.addClickHandler(new ClickHandler() {
                            @Override
                            public void onClick(ClickEvent clickEvent) {
                                dialogBox.hide();
                            }
                        });
                        dialogBoxButtons.add(ok);
                        dialogPanel.add(dialogBoxButtons);
                        dialogBox.add(dialogPanel);
                        dialogBox.show();
                    }
                };
                User user = AspectKnowledgeBaseApplication.get().getUser();
                user.setPassword(confirmPassword);
                    registrationService.updatePassword(user, oldPassword, registration);
            }

        }
    }
}